package display {
	import flare.display.DirtySprite;
	
	import flash.display.Graphics;
	import flash.display.GraphicsPathCommand;
	import flash.display.Sprite;
	import flash.events.Event;

	[SWF(frameRate='10')]
	public class ParticleSprite extends DirtySprite {
		public static var throwDistance:Number = 200;
		
		public var index:int;
		
		public var ox:Number, oy:Number;
		public var px:Number, py:Number;
		public var ppx:Number, ppy:Number;
		
		public var vx:Number = 0, vy:Number = 0;
		public var particleColor:Number;
		
		public var throwAmount:Number = 3 + Math.random() * 98;
		public var snapBack:Number = 0.1 + Math.random() * 0.4;
		public var snapValue:Number = 0;
		public var stickiness:Number = 1.0;
		public var rad:Number;
		
		public function ParticleSprite(ox:Number, oy:Number, rad:Number, c:Number) {
			trace('ParticleSprite >', ox, oy, rad, c);
			this.x = px = ppx = ox;
			this.y = py = ppy = oy;
			this.ox = ox;
			this.oy = oy;
			this.rad = rad;
			this.particleColor = c;
			var initV:Number = 100;
			this.vx += -initV / 2 + Math.random() * initV;
			this.vy += -initV / 2 + Math.random() * initV;
			
			this.addEventListener(Event.ENTER_FRAME, onEnterFrame);
		}
		
		private function onEnterFrame(event:Event):void {
			ppx = px;
			ppy = py;
			px = x;
			py = y;
			
			x += vx;
			y += vy;
			
			vx *= 0.8;
			vy *= 0.8;
			
			trace('ParticleSprite >', this.mouseX, this.mouseY);
			var dx:Number = this.mouseX - x;
			var dy:Number = this.mouseY - y;
			var d:Number = Math.sqrt(dx*dx + dy*dy);
			dx /= d;
			dy /= d;
			
			if (d < throwDistance) {
				vx -= dx * throwAmount;
				vy -= dy * throwAmount;
				snapValue += (0.005 - snapValue) * 0.4;
				stickiness *= 0.9;
				stickiness -= 0.01;
				if (stickiness < 0) {
					stickiness = 0;
				}
				vx *= 1 - stickiness;
				vy *= 1 - stickiness;
			} else {
				snapValue += (snapBack - snapValue) * 0.005;
				stickiness += 0.03;
				if (stickiness > 1) {
					stickiness = 1;
				}
			}
			
			dx = ox - x;
			dy = oy - y;
			d = Math.sqrt(dx * dx + dy * dy);
			
			vx += dx * snapValue;
			vy += dy * snapValue;
			
			rad = 3 + d / 10.0;
			
			dirty();
		}
		
		public override function render():void {

			var g:Graphics = this.graphics;
			g.clear();
			if (px != x && py != y) {
//				g.endFill();
				g.lineStyle(rad * 0.15, particleColor);
//				g.beginFill(particleColor);
				var path:Vector.<Number> = new Vector.<Number>();
				var command:Vector.<int> = new Vector.<int>();
				command.push(GraphicsPathCommand.MOVE_TO);
				command.push(GraphicsPathCommand.LINE_TO);
				command.push(GraphicsPathCommand.LINE_TO);
				path.push(x, y);
				path.push(px, py);
				path.push(ppx, ppy);
				g.drawPath(command, path);
//				g.lineTo(x, y);
//				g.endFill();
			}

			g.beginFill(particleColor);
//			g.drawEllipse(x, y, rad*2, rad*2);
			g.drawCircle(x, y, rad);
			g.endFill();
		}
	}
}